import 'package:flutter/material.dart';
import 'package:qyou_app/common/api.dart';
import 'package:qyou_app/common/base.dart';
import 'package:qyou_app/common/http.dart';
import 'package:qyou_app/model/channel.dart';

class ChannelPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ChannelPageState();
}

class _ChannelPageState extends State<ChannelPage> with Base {
  //包存数据
  List<Channel> channels = [];

  //获取导航列表信息
  void _getChannelData() {
    HttpKit().get(Api.channel).then((value) {
      var navMap = value.data;
      List<Channel> channelList = (navMap as List<dynamic>)
          .map((e) => Channel.fromJson((e as Map<String, dynamic>)))
          .toList();
      setState(() {
        channels = channelList;
      });
    });
  }

  //初始化数据
  @override
  void initState() {
    if (channels == null || channels.length <= 0) {
      _getChannelData();
    }
  }

  Widget _contentPage() {
    return GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4, childAspectRatio: 1.0),
        itemCount: channels.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () => Navigator.of(context).pushNamed(channels[index].route),
            child: Container(
              margin: EdgeInsets.all(dp(20)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Image.asset(channels[index].icon),
                  Padding(padding: EdgeInsets.symmetric(vertical: dp(2))),
                  Text(
                    channels[index].name,
                    style:
                        TextStyle(color: Color(0xFF616161), fontSize: dp(12)),
                  ),
                ],
              ),
            ),
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text("频道"),
        leading: IconButton(
            icon: Icon(
              Icons.arrow_back_rounded,
              color: Color(0xFF757575),
            ),
            onPressed: () {
              Navigator.of(context).pushReplacementNamed("/index");
            }),
      ),
      body: _contentPage(),
    );
    //return
  }
}
